package TCP;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author 宋鑫宇
 * @version 1.0
 * 使用Socket 编写服务端,接收数据
 */
public class ServiceDemo2 {
    public static void main(String[] args) throws Exception {
        //1.注册端口,端口号必须和客户端一致
        ServerSocket ss = new ServerSocket(7777);

        //2.必须调用 accept 方法，等待接收客户端连接请求，建立Socket通信管道
        Socket accept = ss.accept();
        //3.从Socket管道中得到一个字节输入流
        InputStream inputStream = accept.getInputStream();
        //4.把字节输入流包装成字符输入流来接收文本消息
        BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
        //5.读取消息
        String msg;
        //循环接收到消息，如果没有消息后会报错
        if ((msg = br.readLine()) != null) {
            System.out.println(accept.getRemoteSocketAddress() + "发来了：" + msg);
        }
    }
}
